package com.rui1024.servlet;

import com.rui1024.dao.DiaryDao;
import com.rui1024.dao.DiaryTypeDao;
import com.rui1024.dao.impl.DiaryDaoImpl;
import com.rui1024.dao.impl.DiaryTypeDaoImpl;
import com.rui1024.pojo.Diary;
import com.rui1024.pojo.DiaryType;
import com.rui1024.util.JDBCUtil;
import com.rui1024.util.PageUtil;
import com.rui1024.util.PropertiesUtil;
import com.rui1024.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class MainServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        DiaryDao diaryDao = new DiaryDaoImpl();
        DiaryTypeDao diaryTypeDao = new DiaryTypeDaoImpl();
        JDBCUtil jdbcUtil = new JDBCUtil();

        String page = req.getParameter("page");
        String s_typeId = req.getParameter("s_typeId");
        String s_releaseDateStr = req.getParameter("s_releaseDateStr");
        String all = req.getParameter("all");
        String s_title = req.getParameter("s_title");

        HttpSession session = req.getSession();

        Diary s_diary = new Diary();
        // 首页分页，点击下一页防止参数丢失，放在session中
        if(StringUtil.isNotEmpty(s_typeId)){
            s_diary.setTypeId(Integer.parseInt(s_typeId));
            session.setAttribute("s_typeId",s_typeId);
            session.removeAttribute("s_releaseDateStr");
            session.removeAttribute("s_title");
        }
        // 首页分页，点击下一页防止参数丢失，放在session中
        if(StringUtil.isNotEmpty(s_releaseDateStr)){
            // sql在执行查询过程中如果日期参数是需要重新格式化，否则乱码
            // s_releaseDateStr = new String(s_releaseDateStr.getBytes("ISO-8859-1"), "UTF-8");
            s_diary.setReleaseDateStr(s_releaseDateStr);
            session.setAttribute("s_releaseDateStr",s_releaseDateStr);
            session.removeAttribute("s_typeId");
            session.removeAttribute("s_title");
        }
        // 首页分页，点击下一页防止参数丢失，放在session中
        if(StringUtil.isNotEmpty(s_title)){
            s_diary.setTitle(s_title);
            session.setAttribute("s_title",s_title);
            session.removeAttribute("s_typeId");
            session.removeAttribute("s_releaseDateStr");
        }

        // 首页查询所有日志列表,移除session中的所有参数
        if("true".equals(all)){
            session.removeAttribute("s_releaseDateStr");
            session.removeAttribute("s_typeId");
            session.removeAttribute("s_title");
        }
        // 首页分页，点击下一页带上参数
        if(StringUtil.isEmpty(s_typeId)){
            Object o = session.getAttribute("s_typeId");
            if(o!=null){
                s_diary.setTypeId(Integer.parseInt((String)o));
            }
        }
        // 首页分页，点击下一页带上参数
        if(StringUtil.isEmpty(s_releaseDateStr)){
            Object o = session.getAttribute("s_releaseDateStr");
            if(o!=null){
                s_diary.setReleaseDateStr((String)o);
            }
        }
        // 首页分页，点击下一页带上参数
        if(StringUtil.isEmpty(s_title)){
            Object o = session.getAttribute("s_title");
            if(o!=null){
                s_diary.setTitle((String)o);
            }
        }

        if(StringUtil.isEmpty(page)){
            page="1";
        }
        Connection con = null;
        try {
            con = jdbcUtil.getCon();
            PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(PropertiesUtil.getValue("pageSize")));

            List<Diary> diaryList = diaryDao.diaryList(con, pageUtil,s_diary);
            req.setAttribute("diaryList",diaryList);

            List<DiaryType> diaryTypeCountList = diaryTypeDao.diaryTypeCountList(con);
            // 除了主页，添加日志也需要用到类别，所以放在session中
            session.setAttribute("diaryTypeCountList",diaryTypeCountList);

            List<Diary> diaryCountList = diaryDao.diaryCountList(con);
            session.setAttribute("diaryCountList",diaryCountList);


//            前端生成分页代码数据
//            int totalNum = diaryDao.diaryCount(con);
//            int pageSize=Integer.parseInt(PropertiesUtil.getValue("pageSize"));
//            int totalPage=totalNum%pageSize==0?totalNum/pageSize:totalNum/pageSize+1;
//            req.setAttribute("pageSize",Integer.parseInt(PropertiesUtil.getValue("pageSize")));
//            req.setAttribute("currentPage",Integer.parseInt(page));
//            req.setAttribute("totalPage",totalPage);

            req.setAttribute("pageCode",this.genPageCode(diaryDao.diaryCount(con,s_diary),Integer.parseInt(PropertiesUtil.getValue("pageSize")),Integer.parseInt(page)));
            req.setAttribute("mainPage","diary/diaryList.jsp");
            req.getRequestDispatcher("mainTemp.jsp").forward(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                jdbcUtil.closeCon(con);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 后端生成分页代码
     * @param totalNum
     * @param pageSize
     * @param currentPage
     * @return
     */
    public String genPageCode(int totalNum,int pageSize,int currentPage){
        int totalPage=totalNum%pageSize==0?totalNum/pageSize:totalNum/pageSize+1;
        StringBuffer pageCode=new StringBuffer();
        pageCode.append("<li><a href='main?page=1'>首页</a></li>");

        if(currentPage==1){
            pageCode.append("<li class='disabled'><a href='#'>上一页</a></li>");
        }else{
            pageCode.append("<li><a href='main?page="+(currentPage-1)+"'>上一页</a></li>");
        }

        for (int i = currentPage-2; i <=currentPage+2 ; i++) {
            if(i<1 || i>totalPage){
                continue;
            }
            if(i==currentPage){
                pageCode.append("<li class='active'><a href='#'>"+i+"</a></li>");
            }else{
                pageCode.append("<li><a href='main?page="+i+"'>"+i+"</a></li>");
            }
        }

        if(currentPage==totalPage){
            pageCode.append("<li class='disabled'><a href='#'>下一页</a></li>");
        }else{
            pageCode.append("<li><a href='main?page="+(currentPage+1)+"'>下一页</a></li>");
        }

        pageCode.append("<li><a href='main?page="+totalPage+"'>尾页</a></li>");
        return pageCode.toString();
    }
}
